import StateTab from '@/components/StateTab';
import { ConnectState } from '@/models/connect';
import { Form, Input, InputNumber, message, Modal, Popconfirm, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import ExportFormData from '@/components/ExportFormData';
import styles from './index.less';
import { boundMember, getMemberData, unboundMember } from './service';

const { log } = console;

let memberItem: {} = {
  state: 0,
};

const Member = ({ currentUser }) => {
  const [loading, setLoading] = useState<boolean>(true);
  const [dataSource, setDataSource] = useState<[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [visible, setVisible] = useState<boolean>(false);
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);

  const [pageCurrent, setPageCurrent] = useState<number>(1);
  const [form] = Form.useForm();

  const memberDataView = async (pageIndex = 1, pageSize = 10) => {
    const { phone } = currentUser;
    const { state } = memberItem;
    setLoading(true);
    setPageCurrent(pageIndex);
    const { code, data } = await getMemberData({
      phone,
      status: state || 0,
      pageIndex,
      pageSize,
    }).catch(() => {
      message.info('请求数据失败');
      setLoading(false);
    });

    log('memberDataView code', code);
    if (code === undefined || code != 0) {
      // message.info('请求数据失败');
      setLoading(false);
      return;
    }

    const list =
      data.memberDataList &&
      data.memberDataList.map((item: any, index: number) => {
        return {
          key: index,
          name: item.memberName,
          telphone: item.memberPhone,
          ratio: item.bindingScale,
          time: item.bingdingTime,
          handle: item.bindingStatus,
        };
      });

    setDataSource(list);
    setTotal(data.total);
    setLoading(false);
  };

  useEffect(() => {
    memberDataView();
  }, []);

  const selectTab = async (item: any) => {
    memberItem = item;
    memberDataView();
  };

  const unboundConfirm = async (index) => {
    const { phone } = currentUser;
    const { code, info } = await unboundMember({ memberPhone: dataSource[index].telphone, phone });
    if (code != 0) {
      message.error(`解绑失败,${info}`);
      return;
    }

    const list = dataSource;
    list[index].handle = 2;
    setDataSource([...list]);
    message.success('解绑成功');
  };

  const handleCancel = () => {
    setVisible(false);
  };

  const boundConfirm = async (params) => {
    const { phone } = currentUser;
    const { code, info } = await boundMember({ phone, ...params });
    setConfirmLoading(false);

    // 0绑定成功/1不匹配/2待审核/3审核不通过/4已绑定到本账号/5已绑定到其他账号
    if (code != 0) {
      // let str = ''
      // code == 1 && (str = '未能找到此成员信息，请联系兼职注册')
      // code == 2 && (str = '账号审核中，请等待审核通过后再绑定')
      // code == 3 && (str = '账号审核不通过，无法绑定')
      // code == 4 && (str = '账号已绑定，请不要重复绑定')
      // code == 5 && (str = '此成员已绑定到其他组长下，无法绑定')
      message.error(info);
      return;
    }

    form.resetFields();
    message.success('绑定成功');
    handleCancel();
  };

  const tabColumns = [
    {
      key: 'title',
      text: '成员状态',
    },
    {
      key: 'tab',
      text: '全部',
      state: 0,
    },
    {
      key: 'tab',
      text: '已绑定',
      state: 1,
    },
    {
      key: 'tab',
      text: '已解绑',
      state: 2,
    },
  ];

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '手机号码',
      dataIndex: 'telphone',
      key: 'telphone',
    },
    {
      title: '抽成比例',
      dataIndex: 'ratio',
      key: 'ratio',
    },
    {
      title: '绑定时间',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      render: (handleState: number, item) =>
        handleState === 1 ? (
          <Popconfirm
            title="确定要解绑这个成员吗？"
            onConfirm={() => {
              unboundConfirm(item.key);
            }}
            okText="确定"
            cancelText="取消"
          >
            <a>解绑</a>
          </Popconfirm>
        ) : (
          <span>-</span>
        ),
    },
  ];

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };

  const handleOk = () => {
    const formParams = form.getFieldValue();
    form
      .validateFields()
      .then(() => {
        // onCreate(values);
        setConfirmLoading(true);
        boundConfirm(formParams);
      })
      .catch((info) => {
        console.log('Validate Failed:', info);
      });
  };

  // const confirmLoading = () => {

  // }

  return (
    <div className={styles.main}>
      <StateTab className={styles['tab-view']} tabs={tabColumns} selectTab={selectTab}>
        <div
          className={styles['member-btn']}
          onClick={() => {
            setVisible(true);
          }}
        >
          绑定成员
        </div>
      </StateTab>

      <ExportFormData
        action="/service/partTimerWb/group/export"
        data={{ phone: currentUser.phone, status: memberItem.state }}
        count={total}
        columns={['姓名', '手机号码', '抽成比例', '绑定时间', '操作']}
        afterRequest={(response) => {
          const list = response.data.map((item) => {
            const { memberName, memberPhone, bindingScale, bingdingTime, bindingStatus } = item;
            return {
              memberName,
              memberPhone,
              bindingScale,
              bingdingTime,
              handle: bindingStatus === 1 ? '解绑' : '-',
            };
          });
          return list;
        }}
      />
      <Modal
        title="绑定成员"
        visible={visible}
        confirmLoading={confirmLoading}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          layout="horizontal"
          name="form_in_modal"
          // initialValues={{ modifier: 'public' }}
        >
          <Form.Item
            {...formItemLayout}
            name="memberName"
            label="姓名："
            rules={[
              { required: true, message: '请填写姓名' },
              { pattern: /^[\u4e00-\u9fa5]{1,10}$/, message: '请填写正确的姓名' },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            {...formItemLayout}
            name="memberPhone"
            label="手机号码："
            rules={[
              { required: true, message: '请填写手机号码' },
              { pattern: /^1(\d){10}$/, message: '手机号格式错误' },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item className={styles['form-scale-box']} label="抽成比例：" {...formItemLayout}>
            <Form.Item
              name="scale"
              noStyle
              rules={[
                { required: true, message: '请填写抽成比例' },
                { pattern: /^([0-9]{1,2}|100)$/, message: '抽成比例需在0-100之间' },
              ]}
            >
              <InputNumber style={{ width: 326 }} className={styles['form-scale']} />
            </Form.Item>
            <span>%</span>
          </Form.Item>
          <p className={styles['form-tip']}>兼职每做一条内容，你能拿到的收益分成比例</p>
        </Form>
      </Modal>

      <Table
        dataSource={dataSource}
        loading={loading}
        columns={columns}
        pagination={{
          pageSize: 10,
          total,
          current: pageCurrent,
          onChange: (index) => {
            memberDataView(index);
          },
        }}
        bordered
      />
    </div>
  );
};

export default connect(({ user: { currentUser } }: ConnectState) => ({
  currentUser,
}))(Member);
